package brouter.api;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

import brouter.annotation.bean.RouterBean;
import brouter.api.utils.PathUtil;

public class RouterManager {
    private static final String TAG = "RouterManager";
    private String group;
    private String path;
    private Map<String, Map<String, RouterBean>> allPathMap;
    // 通过集合优化反射带来的性能损耗，BRouterPath 个数是模块的数量，数量不多，故无需LruCache做优化
    private Map<String, BRouterPath> routerPathMap;

    // 单例模式
    private static RouterManager instance;

    private RouterManager() {
        routerPathMap = new HashMap<>();
    }

    public static RouterManager getInstance() {
        if (instance == null) {
            synchronized (RouterManager.class) {
                if (instance == null) {
                    instance = new RouterManager();
                }
            }
        }
        return instance;
    }

    public BundleManager build(String path) {
        if (!PathUtil.checkRouterPath(path)) {
            throw new IllegalArgumentException("不按常理出牌 path乱搞的啊，正确写法：如 /login/LoginActivity");
        }
        this.path = path;
        this.group = PathUtil.parseGroup(path);
        return new BundleManager(); // Builder设计模式 之前是写里面的， 现在写外面吧
    }

    public Object navigation(Context context, BundleManager bundleManager) {
        String routerClsName = context.getPackageName() + ".BRouterPath$$" + group;
        try {
            BRouterPath routerPath = routerPathMap.get(group);
            if (routerPath == null) {
                Class<?> clz = Class.forName(routerClsName);
                routerPath = (BRouterPath) clz.newInstance();
                routerPathMap.put(group, routerPath);
            }

            allPathMap = routerPath.getPathMap();
            Map<String, RouterBean> pathMap = allPathMap.get(group);
            RouterBean routerBean = pathMap.get(path);
            Log.i(TAG, "navigation: " + routerBean);
            if (routerBean != null) {
                switch (routerBean.getType()) {
                    case ACTIVITY:
                        Intent intent = new Intent(context, routerBean.getMyClass());
                        intent.putExtras(bundleManager.getBundle());
                        context.startActivity(intent);
                        break;
                    case CALL:
                        Class<?> myClass = routerBean.getMyClass();
                        return myClass.newInstance();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
